<template>
  <MenuPage
    inner
    ref="selectTable"
    title="成员管理"
    :columns="userCol"
    :data="exGroupMemberList"
    :total="exGroupMemberList.length"
    noDataText="暂无数据"
    :showPage="false"
    showSelectTag
    :selectName="(item) => item.user && item.user.nickname"
    :selection.sync="checkedData">
      <template slot="search">
        <Poptip
        transfer
        confirm
        title="确定要移除选中的成员吗？"
        placement="left"
        :disabled="setBtnStatus() || !checkedData.length"
        @on-ok="batchDelete"
      >
        <Button
          type="error"
          :disabled="setBtnStatus() || !checkedData.length"
          icon="md-remove"
          style="margin-right: 10px;"
          >批量删除</Button
        >
      </Poptip>
      <Button type="primary" class="md-add-jh" @click="showDrawerBtn" :disabled="setBtnStatus()"
        >添加成员</Button
      >
    </template>
  <Modal
      :closable="true"
      :mask-closable="false"
      width="1000"
      v-model="addDeviceModel"
      @on-visible-change="changeModalStatus"
      title="添加成员"
      :footer-hide="true"
    >
      <div style="display: flex;justify-content: flex-end;margin-top: 15px">
        <Input
          v-model.trim="addSearchComMemInput"
          placeholder="用户名"
          style="width: 150px;margin-right: 15px"
          clearable
          @on-change="addSearchComMem"
        />
        <Button title="重置" @click="refreshAddGroupList"
          ><i class="el-icon-refresh-right"
        /></Button>
      </div>
      <div>
        <div class="tag-wrap-div">
          <Tag
            v-for="item in getAddMemIdArr"
            :key="item"
            :name="item"
            closable
            @on-close="handleClose2"
            >{{ handleTagName(item) }}</Tag
          >
        </div>
        <Table
          :columns="addGroupMemCol"
          :data="addGroupMemList"
          :max-height="setUserTableHei"
          @on-select="selectSignal"
          @on-select-cancel="cancelSelectSignal"
          @on-select-all="selectAll"
          @on-select-all-cancel="cancelSelectAll"
        ></Table>
        <div class="table-bottom">
          <div style="display: flex;justify-content: flex-start;align-items: center">
            <Button
              style="margin-right: 15px"
              type="primary"
              @click="addAssign"
              :loading="submitAddMemLoading"
              >添加</Button
            >
            <Button @click="addDeviceModel = false">取消</Button>
          </div>
          <Page
            :current="addGroupMemPage"
            :total="addGroupTotal"
            :page-size="addGroupPageSize"
            show-total
            show-elevator
            @on-change="addGroupOnChange"
          />
        </div>
      </div>
    </Modal>
</MenuPage>
</template>
<script>
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import {
  getGroupMembers,
  getExperOfCompany,
  addMembersForGroup,
  removeMemberByGroup,
  batchRemoveMemberByGroup
} from '@/api/company.js';
export default {
  components: {},
  data() {
    return {
      checkAll: false,
      checkedData: [],
      // 人员信息
      USER_ID: '',
      isRootDesigner: false,
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setUserTableHei: '700',
      // 显示
      showDefImg: false,
      showImgList: false,
      // 实验组id
      groupId: '',
      groupName: '',
      // 用户组成员
      exGroupMemberList: [],
      userCol: [
        {
          type:'selection',
          width:60
        },
        {
            title: '用户名',
            key: 'username',
            align: 'left',
            tooltip: true,
            filter:(username,user) => {
              return user && user.user.username
            }
        },
        {
            title: '昵称',
            key: 'nickname',
            align: 'left',
            tooltip: true,
            filter:(username,user) => {
              return user && user.user.nickname
            }
        },
        {
            title: '单位',
            key: 'companyName',
            align: 'left',
            tooltip: true,
            filter:(username,user) => {
              return user && user.user.companyName
            }
        },
        {
            title: '邀请人',
            key: 'inviterName',
            align: 'left',
            tooltip: true
        },
        {
            title: '受邀状态',
            key: 'status',
            align: 'left',
            tooltip: true,
            filter: (status, data) => {
                return this.setStatus(data);
            }
        },
        {
            title: '类型',
            key: 'type',
            align: 'left',
            tooltip: true,
            filter: (type, data) => {
                return this.setType(data.user);
            }
        },
        // {
        //     title: '特权等级',
        //     key: 'identification',
        //     align: 'left',
        //     tooltip: true,
        //     filter: (type, data) => {
        //         return this.setIdentification(data);
        //     }
        // },
        {
          title:'靶场来源',
          key: 'rangeName',
          align: 'left',
          tooltip: true,
          filter:(rangeName,user) => {
            return user && user.user.rangeName
          }
        },
        {
            type: 'Tag',
            title: '在线',
            key: 'online',
            align: 'left',
            width: 90,
            filter: (online) => {
                return online ? '是' : '否';
            },
            setColor: (online) => {
                return online ? 'var(--status-yes)': 'var(--status-no)';
            }
        },
        {
            title: '操作',
            slot: 'action',
            width: 80,
            opList: [
                {
                    txt: '移除',
                    type: 'delete',
                    tooltip: true,
                    title: '确定要移除该成员吗？',
                    disEdit: (data) => this.setIsClick(data) ? true : false,
                    fun: this.delMember
                }
            ]
        }
    ],
      // 添加成员 单位内成员
      addDeviceModel: false,
      addGroupMemPage: 1,
      addGroupTotal: 0,
      addGroupPageSize: 10,
      addGroupMemList: [],
      addGroupMemCol: [
        {
          type: 'selection',
          width: 60,
          align: 'left',
          render: (h, params) => {
            return h('div', {
              style: {
                display: 'none'
              }
            });
          }
        },
        {
          title: '用户名称',
          key: 'username',
          align: 'left'
        },
        {
          title: '昵称',
          key: 'nickname',
          align: 'left'
        },
        {
          title: '类型',
          key: 'type',
          align: 'left',
          render: (h, params) => {
            return h('span', this.setType(params.row));
          }
        },
        // {
        //     title:'角色',
        //     key:'role',
        //     align:'left'
        // },
        {
          title: '是否在线',
          key: 'online',
          align: 'left',
          width: 90,
          render: (h, params) => {
            let text = '';
            if (!params.row.online || params.row.online === 'false') {
              text = 'default';
            } else {
              text = 'success';
            }
            return h(
              'Tag',
              {
                props: {
                  color: text,
                  type: 'border'
                }
              },
              this.isOnline(params.row.online).text
            );
          }
        },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'left'
        },
        {
          title: '创建时间',
          key: 'created',
          align: 'left',
          width: 170,
          // sortable: true,
          // sortType: 'desc'
        }
      ],
      getAddMemIdArr: [],
      submitAddMemLoading: false,
      addSearchComMemInput: '',
      saveMemberIdArr: [],
      // 删除icon
      delImg: require('../../assets/project/delNote-h.png')
    };
  },
  computed: {
    pageTitle () {
      //当前菜单显示名
      return this.$route.meta.title;
    },
  },
  created() {},
  mounted() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.groupId = this.$route.query.id;
    this.groupName = this.$route.query.name;
    this.addBreadItem({ name: this.groupName });
    this.groupCreator = this.$route.query.creator;
    // this.setStyle();
    // window.onresize = () => {
    //   this.setStyle();
    // };
    // 获取实验组的成员
    this.getMembers();
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/experGroup') {
      //to.query.page = this.$route.query.page
      next();
    } else {
      sessionStorage.removeItem('queryObj');
      next();
    }
  },
  methods: {
    selectAllChange(type) {
      this.exGroupMemberList.forEach((item) => (item.checked = type));
      if (type) {
        this.checkedData = this.exGroupMemberList.map((item) => {
          return {
            userId: item.userId,
            userName: item.user && item.user.username
          };
        });
      } else {
        this.checkedData = [];
      }
    },
    removeData(data) {
      const index = this.checkedData.findIndex((item) => item.userId === data.userId);
      if (index !== -1) {
        this.checkedData.splice(index, 1);
      }
      const item = this.exGroupMemberList.find((item) => item.userId === data.userId);
      if (item) {
        item.checked = false;
      }
      this.checkAll = false;
    },
    changeCheckedData(type, userId, userName) {
      if (type) {
        this.checkedData.push({
          userId,
          userName
        });
      } else {
        const index = this.checkedData.findIndex((item) => item.userId === userId);
        if (index !== -1) {
          this.checkedData.splice(index, 1);
        }
      }
      // 有任何一条数据没选中，全选就不选中
      this.checkAll = !this.exGroupMemberList.some((item) => !item.checked);
    },
    batchDelete() {
      batchRemoveMemberByGroup(
        this.groupId,
        this.checkedData.map((item) => item.userId)
      )
        .then(({ data = {} }) => {
          let { code, message } = data;
          if (code === 1) {
            this.$Message.success('批量移出成功');
            this.getMembers();
            this.checkAll = false;
            this.checkedData = [];
          } else {
            this.$Message.warning(message);
          }
        })
        .catch((err) => {
          this.$Message.error('批量移出异常');
        });
    },
    setType(val) {
      let text = '';
      if (val.type === 'designer') {
        if (val.role === 'evaluator') {
          text = '评估人员';
        }
        if (val.role === 'leader') {
          text = '单位管理员';
        }
        if (val.role === 'member') {
          text = '单位设计师';
        }
      } else if (val.type === 'experimenter') {
        text = '操作员';
      }
      return text;
    },
    setStatus(val) {
      if (val == 'confirmed') {
        return '已受邀';
      } else {
        return '未受邀';
      }
    },
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
    },
    // 返回单位
    returnCompany() {
      this.$router.push({
        name: 'memberManagement',
        query: {
          page: this.$route.query.page
        }
      });
    },
    // 获取实验组的成员
    getMembers() {
      this.checkedData = [];
      this.saveMemberIdArr = [];
      getGroupMembers(this.groupId)
        .then((res) => {
          if (res.data.code == 1) {
            let getData = res.data.data;
            console.log(getData);
            for (let i = 0; i < getData.length; i++) {
              if (getData[i]['user']) {
                getData[i].online = getData[i].user.online;
                this.saveMemberIdArr.push(getData[i]['user']['id']);
              }
            }
            console.log(this.saveMemberIdArr);
            this.exGroupMemberList = getData;
            if (getData.length > 0) {
              this.showDefImg = false;
              this.showImgList = true;
            } else {
              this.showDefImg = true;
              this.showImgList = false;
            }
          } else {
            this.$Message.error('成员列表查询失败！');
            this.showDefImg = true;
            this.showImgList = false;
          }
        })
        .catch((err) => {
          console.log(err);
          this.showDefImg = true;
          this.showImgList = false;
        });
    },
    // 删除成员
    delMember(row) {
      let params = {
        groupId: this.groupId,
        userId: row.userId
      };
      removeMemberByGroup(params)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success({
              content: '移出成功！',
              duration: 3
            });
            this.getMembers();
            this.$refs.selectTable.closeItem(row)
          } else {
            this.$Message.error({
              content: '移出失败！',
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 单位内成员
    showDrawerBtn() {
      this.addDeviceModel = true;
      let params = {
        pageIndex: this.addGroupMemPage,
        pageSize: this.addGroupPageSize,
        type: 'experimenter',
        order: 'desc',
        sortBy: 'created'
      };
      if (!this.isRootDesigner) {
        params.creator = this.USER_ID;
      }
      if (this.addSearchComMemInput != '') {
        params.username = this.addSearchComMemInput;
      }
      getExperOfCompany(params)
        .then((res) => {
          if (res.data.code == 1) {
            let getData = res.data.data;
            this.addGroupTotal = getData.total;

            let items = getData.items;
            for (let i = 0; i < items.length; i++) {
              items[i]._checked = false;
              items[i]._disabled = false;
              if (this.saveMemberIdArr.indexOf(items[i]['id']) > -1) {
                items[i]._disabled = true;
              }
              let IDJoinName = items[i].id + '_._' + items[i].username;
              if (this.getAddMemIdArr.indexOf(IDJoinName) > -1) {
                items[i]._checked = true;
              }
            }
            this.addGroupMemList = items;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    closeDistribution() {
      this.addDeviceModel = false;
    },
    changeModalStatus(val) {
      if (!val) {
        this.getAddMemIdArr = [];
      }
      this.addSearchComMemInput = '';
      this.addGroupMemPage = 1;
      this.addGroupPageSize = 10;
    },
    addGroupOnChange(val) {
      this.addGroupMemPage = val;
      this.showDrawerBtn();
    },
    addSearchComMem(val) {
      this.addGroupMemPage = 1;
      this.addSearchComMemInput = this.addSearchComMemInput;
      this.showDrawerBtn();
    },
    refreshAddGroupList() {
      this.addGroupMemPage = 1;
      this.addSearchComMemInput = '';
      this.showDrawerBtn();
    },
    addAssign() {
      if (this.getAddMemIdArr.length === 0) {
        this.$Message.error({
          content: '请选择需要添加的成员！',
          duration: 3
        });
        return false;
      }
      let arr = [];
      for (let i = 0; i < this.getAddMemIdArr.length; i++) {
        let getID = this.getAddMemIdArr[i].split('_._')[0];
        arr.push(getID);
      }
      this.submitAddMemLoading = true;
      addMembersForGroup(this.groupId, arr)
        .then((res) => {
          if (res.data.code === 1) {
            if (res.data.data.length > 0) {
              this.$Message.success({
                content: '添加成功！',
                duration: 3
              });
              this.getMembers();
              this.addDeviceModel = false;
            }
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
          this.submitAddMemLoading = false;
        })
        .catch((err) => {
          this.submitAddMemLoading = false;
          console.log(err);
        });
    },
    // 点击添加一个
    selectSignal(val, row) {
      let IDJoinName = row.id + '_._' + row.username;
      if (this.getAddMemIdArr.indexOf(IDJoinName) <= -1) {
        this.getAddMemIdArr.push(IDJoinName);
        this.modifyCheckStatus(row, true);
      }
    },
    // 点击删除一个
    cancelSelectSignal(val, row) {
      let IDJoinName = row.id + '_._' + row.username;
      if (this.getAddMemIdArr.indexOf(IDJoinName) > -1) {
        let index = this.getAddMemIdArr.indexOf(IDJoinName);
        this.getAddMemIdArr.splice(index, 1);
        this.modifyCheckStatus(row, false);
      }
    },
    // 点击添加一页
    selectAll(val) {
      for (let i = 0; i < this.addGroupMemList.length; i++) {
        let IDJoinName = this.addGroupMemList[i].id + '_._' + this.addGroupMemList[i].username;
        this.$set(this.addGroupMemList[i], '_checked', true);
        if (this.getAddMemIdArr.indexOf(IDJoinName) <= -1 && !this.addGroupMemList[i]._disabled) {
          this.getAddMemIdArr.push(IDJoinName);
        }
      }
    },
    // 点击取消一页
    cancelSelectAll(val) {
      for (let i = 0; i < this.addGroupMemList.length; i++) {
        let IDJoinName = this.addGroupMemList[i].id + '_._' + this.addGroupMemList[i].username;
        this.$set(this.addGroupMemList[i], '_checked', false);
        if (this.getAddMemIdArr.indexOf(IDJoinName) > -1 && !this.addGroupMemList[i]._disabled) {
          let index = this.getAddMemIdArr.indexOf(IDJoinName);
          this.getAddMemIdArr.splice(index, 1);
        }
      }
    },
    // 显示tag的名称
    handleTagName(item) {
      return item.split('_._')[1];
    },
    // 点击tag
    handleClose2(event, name) {
      if (this.getAddMemIdArr.indexOf(name) > -1) {
        let index = this.getAddMemIdArr.indexOf(name);
        this.getAddMemIdArr.splice(index, 1);
        let id = name.split('_._')[0];
        for (let i = 0; i < this.addGroupMemList.length; i++) {
          if (id === this.addGroupMemList[i].id) {
            this.$set(this.addGroupMemList[i], '_checked', false);
          }
        }
      }
    },
    // 修改选中状态
    modifyCheckStatus(val, status) {
      for (let i = 0; i < this.addGroupMemList.length; i++) {
        if (val.id === this.addGroupMemList[i].id) {
          this.$set(this.addGroupMemList[i], '_checked', status);
        }
      }
    },
    // 是否在线
    isOnline(val) {
      let text = '';
      let color = '';
      let obj = {};
      if (val) {
        text = '是';
        color = '#90EE90';
      } else {
        text = '否';
      }
      obj.text = text;
      obj.color = color;
      return obj;
    },
    setBtnStatus() {
      return this.groupCreator !== this.USER_ID && !this.isRootDesigner;
    },
    // 是否可以删除
    setIsClick() {
      if (this.groupCreator !== this.USER_ID && !this.isRootDesigner) {
        return { 'pointer-events': 'none' };
      }
    },
    setDelImgSrc() {
      if (this.groupCreator !== this.USER_ID && !this.isRootDesigner) {
        return require('../../assets/project/delNote-d.png');
      } else {
        return require('../../assets/project/delNote-h.png');
      }
    }
  }
};
</script>
<style scoped>
.table-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /*margin-top: 15px;*/
  padding: 15px 10px 10px 19px;
  /* border-left: 1px solid #e8eaec;
  border-bottom: 1px solid #e8eaec;
  border-right: 1px solid #e8eaec; */
}
.tag-wrap-div {
  max-height: 100px;
  margin-bottom: 15px;
  margin-top: 10px;
  overflow-y: auto;
}
</style>
